package ae.pcfc.etks.online.web.controller.admin.general.service.register;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;

import ae.pcfc.etks.online.common.ConstantsCommon;
import ae.pcfc.etks.online.common.delegate.ServiceDelegate;
import ae.pcfc.etks.online.common.delegate.UtilityDelegate;
import ae.pcfc.etks.online.common.vo.ClientRoleVO;
import ae.pcfc.etks.online.common.vo.DepartmentVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.PagingVO;
import ae.pcfc.etks.online.common.vo.ServiceVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.JQGridJSONModel;
import ae.pcfc.etks.online.web.model.Service;

/* $Id: AdminListServiceController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * May 08, 2011 	Neha_Chauhan 	        Created
 *
 */

/**
 * Controller that handles all {@link AdminListServiceController}-related
 * requests, i.e.: all requests for /admin/general/service/register/*
 * 
 * @author Neha Chauhan
 */

@Controller
@RequestMapping(ViewPath.ADMIN_REGISTER_SERVICE)
public class AdminListServiceController extends BaseController{

	private ServiceDelegate serviceDelegate;

	@Resource(name = "serviceDelegate")
	public void setServiceDelegate(ServiceDelegate serviceDelegate) {
		this.serviceDelegate = serviceDelegate;
	}

	private UtilityDelegate utilityDelegate;

	@Resource(name = "utilityDelegate")
	public void setUtilityDelegate(UtilityDelegate utilityDelegate) {
		this.utilityDelegate = utilityDelegate;
	}

	@ModelAttribute(value = ConstantsAdmin.ADMIN_SHOW_SERVICE_MODEL_KEY)
	public Service populateUserInfoEdit(HttpServletRequest request, @RequestParam(value = "id", required = false) String id) {

		// TODO Here we'll place the logic to load the Data through an Id
		return new Service();

	}
	@ModelAttribute(ConstantsAdmin.ADMIN_SERVICE_TYPE_LIST)
	public List<LabelVO> populateServiceTypeList(Locale locale) {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();
		labelVO.setId(ConstantsCommon.SERVICE_INTERNAL);
		labelVO.setDisplayLabel(getMessageSource().getMessage(
				"label.service.internal", null, locale));

		labelList.add(labelVO);

		labelVO = new LabelVO();
		labelVO.setId(ConstantsCommon.SERVICE_EXTERNAL);
		labelVO.setDisplayLabel(getMessageSource().getMessage(
				"label.service.external", null, locale));

		labelList.add(labelVO);

		return labelList;
	}
	@RequestMapping(value = "/displayServicesTable")
	public @ResponseBody
	JQGridJSONModel displayServicesTable(HttpServletRequest request, @RequestParam(value = "page", required = true) String page,
			@RequestParam(value = "rows", required = true) String rows,
			@RequestParam(value = "sidx", required = true) String sidx,
			@RequestParam(value = "sord", required = true, defaultValue = "desc") String sord,
			@RequestParam(value = "_search", required = false) String isSearch,
			@RequestParam(value = "searchField", required = false) String searchField,
			@RequestParam(value = "searchOper", required = false) String searchOper,
			@RequestParam(value = "searchString", required = false) String searchString,
			Locale locale) {

		List<String> requestParameterNames = Collections.list((Enumeration<String>) request.getParameterNames());

		for (String parameterName : requestParameterNames) {
			System.out.println("parameterName = " + parameterName);

		}

		JQGridJSONModel result = new JQGridJSONModel();

		Integer pageIndx = 1, count = serviceDelegate.getServicesList().size(), totalpages = 0, start = 0;
		Integer limit = 40;
		try {
			pageIndx = Integer.parseInt(page);
		} catch (Exception nullexp) {
			pageIndx = 1;
		}
		try {
			limit = Integer.parseInt(rows);
		} catch (Exception nullexp) {
			pageIndx = 10;
		}

		if (count > 0)
			totalpages = (int) Math.ceil(((float) count) / (float) limit);
		else
			totalpages = 1;

		if (pageIndx > totalpages)
			pageIndx = totalpages;

		start = (limit * pageIndx) - limit;
		result.setPage(pageIndx.toString());
		result.setRecords(count + "");
		result.setTotal(totalpages + "");
		if(getLog(this.getClass().getName()).isInfoEnabled())
		{
			getLog(this.getClass().getName()).info("Page=" + pageIndx + " , Records=" + limit + " , Total=" + totalpages);
		}

		PagingVO pagingVO = new PagingVO();

		pagingVO.setPageNumber(pageIndx);
		pagingVO.setPageSize(limit);
		pagingVO.setStart(start);
		pagingVO.setSortFieldName(sidx);
		pagingVO.setSortOrder(sord);
		
		pagingVO.setSearchfieldName(searchField);
		pagingVO.setSerachString(searchString);

		List<ServiceVO> serviceVOs = this.serviceDelegate.getServiceListByPagingVO(pagingVO);
		
		if(serviceVOs != null && serviceVOs.size() > 0)
		{
			for (ServiceVO serviceVO : serviceVOs) {
				List<String> cells = new ArrayList<String>();
				cells.add(serviceVO.getStrServiceID().toString());
				cells.add(serviceVO.getStrServiceNameEng());
				cells.add(serviceVO.getStrServiceNameArb());
				if(ConstantsCommon.SERVICE_INTERNAL.equalsIgnoreCase(serviceVO.getStrServiceType())){
					cells.add(getMessageSource().getMessage("label.service.internal", null, locale));	
				}else if(ConstantsCommon.SERVICE_EXTERNAL.equalsIgnoreCase(serviceVO.getStrServiceType())){
					cells.add(getMessageSource().getMessage("label.service.external", null, locale));
				}else{
					cells.add("");
				}
				
				result.addRows(serviceVO.getStrServiceID().toString(), cells);
			}
		}

		return result;

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Boolean delete(HttpServletRequest request, @RequestParam(value = "row", required = true) String row) {

		Boolean rowDel = serviceDelegate.deleteServiceById(Long.valueOf(row));
		return rowDel;

	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * admin/general/service/register/list.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/service/register/list.jsp
	 */

	@RequestMapping(value = "/list.htm", method = RequestMethod.GET)
	public void list(@ModelAttribute(value = ConstantsAdmin.ADMIN_SHOW_SERVICE_MODEL_KEY) Service command) {

	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * admin/general/service/register/list.jsp
	 * 
	 * @see #form(Service)
	 * @see WEB-INF/jsp/admin/general/service/register/list.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/list.htm")
	public String list(HttpServletRequest request, SessionStatus status,
			@ModelAttribute(value = ConstantsAdmin.ADMIN_SHOW_SERVICE_MODEL_KEY) @Valid Service listService, BindingResult errors) {

		boolean isSave = WebUtils.hasSubmitParameter(request, ConstantsAdmin.SAVE_BUTTON);

		if (isSave) {
			if (errors.hasErrors()) {

				return ViewUtils.DEFAULT_VIEW;

			} else {

				String[] messageArgs = new String[] { getMessageSource().getMessage("success.user.info.edit", null,
						RequestContextUtils.getLocale(request)) };

			}

		}
		return ViewUtils.DEFAULT_VIEW;
	}
	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * admin/general/service/register/view/show.htm
	 * 
	 * 
	 * @see WEB-INF/jsp/admin/general/service/register/view/show.jsp
	 */
	@RequestMapping(value = "/view/show.htm", method = RequestMethod.POST)
	public void getServiceInfo(HttpServletRequest request, @RequestParam(value = "serviceId", required = true) String serviceId, Model model) {
		ServiceVO service = serviceDelegate.getServiceByPrimaryKey(Long.valueOf(serviceId));

		if(service != null){

			if(ConstantsCommon.SERVICE_EXTERNAL.equalsIgnoreCase(service.getStrServiceType())){
				List<ClientRoleVO> clientRoleVOList = serviceDelegate.findClientRolesByRoleIds(service.getArrServiceRole());
				if(clientRoleVOList != null){
					service.setListServiceRoles(clientRoleVOList);
				}
				
				List<DepartmentVO> departmentVOList = serviceDelegate.findServiceDepartmentsByDepartmentId(service.getArrServiceDeptsCode());
				if(departmentVOList != null){
					service.setListServiceDepts(departmentVOList);
				}
			}
			model.addAttribute(ConstantsAdmin.ADMIN_SERVICE_INFO_MODEL_KEY, service);
		}

	}
}
